{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "e569a513-67b1-4165-9ce7-d6ff4a68ff93",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeableNote: you may need to restart the kernel to use updated packages.\n",
      "\n",
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/\n",
      "Requirement already satisfied: openai in c:\\users\\10028\\appdata\\roaming\\python\\python313\\site-packages (2.6.0)\n",
      "Requirement already satisfied: anyio<5,>=3.5.0 in d:\\anaconda\\lib\\site-packages (from openai) (4.7.0)\n",
      "Requirement already satisfied: distro<2,>=1.7.0 in d:\\anaconda\\lib\\site-packages (from openai) (1.9.0)\n",
      "Requirement already satisfied: httpx<1,>=0.23.0 in d:\\anaconda\\lib\\site-packages (from openai) (0.28.1)\n",
      "Requirement already satisfied: jiter<1,>=0.10.0 in c:\\users\\10028\\appdata\\roaming\\python\\python313\\site-packages (from openai) (0.11.1)\n",
      "Requirement already satisfied: pydantic<3,>=1.9.0 in d:\\anaconda\\lib\\site-packages (from openai) (2.10.3)\n",
      "Requirement already satisfied: sniffio in d:\\anaconda\\lib\\site-packages (from openai) (1.3.0)\n",
      "Requirement already satisfied: tqdm>4 in d:\\anaconda\\lib\\site-packages (from openai) (4.67.1)\n",
      "Requirement already satisfied: typing-extensions<5,>=4.11 in d:\\anaconda\\lib\\site-packages (from openai) (4.12.2)\n",
      "Requirement already satisfied: idna>=2.8 in d:\\anaconda\\lib\\site-packages (from anyio<5,>=3.5.0->openai) (3.7)\n",
      "Requirement already satisfied: certifi in d:\\anaconda\\lib\\site-packages (from httpx<1,>=0.23.0->openai) (2025.4.26)\n",
      "Requirement already satisfied: httpcore==1.* in d:\\anaconda\\lib\\site-packages (from httpx<1,>=0.23.0->openai) (1.0.9)\n",
      "Requirement already satisfied: h11>=0.16 in d:\\anaconda\\lib\\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.16.0)\n",
      "Requirement already satisfied: annotated-types>=0.6.0 in d:\\anaconda\\lib\\site-packages (from pydantic<3,>=1.9.0->openai) (0.6.0)\n",
      "Requirement already satisfied: pydantic-core==2.27.1 in d:\\anaconda\\lib\\site-packages (from pydantic<3,>=1.9.0->openai) (2.27.1)\n",
      "Requirement already satisfied: colorama in d:\\anaconda\\lib\\site-packages (from tqdm>4->openai) (0.4.6)\n"
     ]
    }
   ],
   "source": [
    "pip install openai -i https://pypi.tuna.tsinghua.edu.cn/simple/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "65fb4c87-b512-4e59-ac4e-be74fe4670ca",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\10028\\AppData\\Local\\Temp\\ipykernel_19772\\1680952751.py:110: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.\n",
      "  chatbot = gr.Chatbot(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7860\n",
      "* To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "# 初始化DeepSeek客户端\n",
    "client = OpenAI(\n",
    "    api_key=\"sk-09f7c0b9b6894868a1d09cfa3c82f2b3\",\n",
    "    base_url=\"https://api.deepseek.com\"\n",
    ")\n",
    "\n",
    "def get_recipe(dish_name):\n",
    "    \"\"\"根据菜名获取本帮菜菜谱\"\"\"\n",
    "    if not dish_name.strip():\n",
    "        return \"请输入一个有效的菜名\"\n",
    "    \n",
    "    try:\n",
    "        # 构建系统提示词，专注于本帮菜菜谱\n",
    "        system_prompt = \"\"\"你是一个专业的本帮菜厨师和美食专家。请为用户提供详细、准确的本帮菜菜谱。\n",
    "        菜谱应该包含以下部分：\n",
    "        1. 菜品简介（本帮菜特色）\n",
    "        2. 所需食材（精确到克或适量）\n",
    "        3. 详细步骤\n",
    "        4. 烹饪技巧和小贴士\n",
    "        请用专业但易懂的语言描述，确保用户能够按照菜谱成功制作。\"\"\"\n",
    "        \n",
    "        user_prompt = f\"请提供本帮菜'{dish_name}'的详细菜谱\"\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=\"deepseek-chat\",\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": system_prompt},\n",
    "                {\"role\": \"user\", \"content\": user_prompt}\n",
    "            ],\n",
    "            stream=False\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "        \n",
    "    except Exception as e:\n",
    "        return f\"获取菜谱时出现错误：{str(e)}\"\n",
    "\n",
    "def chat_with_chef(message, history):\n",
    "    \"\"\"与厨师对话的功能\"\"\"\n",
    "    try:\n",
    "        system_prompt = \"\"\"你是一个热情的本帮菜厨师，精通上海本帮菜的制作。\n",
    "        请用亲切、专业的口吻回答用户关于本帮菜的问题，包括：\n",
    "        - 菜谱查询\n",
    "        - 烹饪技巧\n",
    "        - 食材选择\n",
    "        - 菜品历史和文化\n",
    "        - 其他与本帮菜相关的问题\"\"\"\n",
    "        \n",
    "        # 构建对话历史\n",
    "        messages = [{\"role\": \"system\", \"content\": system_prompt}]\n",
    "        \n",
    "        # 添加历史对话\n",
    "        for user_msg, bot_msg in history:\n",
    "            messages.extend([\n",
    "                {\"role\": \"user\", \"content\": user_msg},\n",
    "                {\"role\": \"assistant\", \"content\": bot_msg}\n",
    "            ])\n",
    "        \n",
    "        # 添加当前消息\n",
    "        messages.append({\"role\": \"user\", \"content\": message})\n",
    "        \n",
    "        response = client.chat.completions.create(\n",
    "            model=\"deepseek-chat\",\n",
    "            messages=messages,\n",
    "            stream=False\n",
    "        )\n",
    "        \n",
    "        return response.choices[0].message.content\n",
    "        \n",
    "    except Exception as e:\n",
    "        return f\"对话时出现错误：{str(e)}\"\n",
    "\n",
    "# 创建Gradio界面\n",
    "with gr.Blocks(theme=gr.themes.Soft(), title=\"本帮菜菜谱助手\") as demo:\n",
    "    gr.Markdown(\n",
    "        \"\"\"\n",
    "        # 🍲 本帮菜菜谱助手\n",
    "        欢迎使用本帮菜菜谱助手！我可以为您提供正宗的本帮菜菜谱和烹饪指导。\n",
    "        \"\"\"\n",
    "    )\n",
    "    \n",
    "    with gr.Tab(\"📖 菜谱查询\"):\n",
    "        with gr.Row():\n",
    "            with gr.Column():\n",
    "                dish_input = gr.Textbox(\n",
    "                    label=\"请输入本帮菜菜名\",\n",
    "                    placeholder=\"例如：红烧肉、糖醋小排、腌笃鲜...\",\n",
    "                    lines=1\n",
    "                )\n",
    "                recipe_btn = gr.Button(\"获取菜谱\", variant=\"primary\")\n",
    "            \n",
    "            with gr.Column():\n",
    "                recipe_output = gr.Textbox(\n",
    "                    label=\"菜谱详情\",\n",
    "                    lines=15,\n",
    "                    interactive=False\n",
    "                )\n",
    "        \n",
    "        # 示例菜名\n",
    "        gr.Examples(\n",
    "            examples=[\"红烧肉\", \"糖醋小排\", \"腌笃鲜\", \"油爆虾\", \"草头圈子\", \"八宝辣酱\"],\n",
    "            inputs=dish_input\n",
    "        )\n",
    "    \n",
    "    with gr.Tab(\"💬 厨师对话\"):\n",
    "        chatbot = gr.Chatbot(\n",
    "            label=\"与本帮菜厨师对话\",\n",
    "            height=400\n",
    "        )\n",
    "        with gr.Row():\n",
    "            msg = gr.Textbox(\n",
    "                label=\"输入您的问题\",\n",
    "                placeholder=\"请问如何制作正宗的上海红烧肉？\",\n",
    "                scale=4\n",
    "            )\n",
    "            send_btn = gr.Button(\"发送\", variant=\"primary\", scale=1)\n",
    "        \n",
    "        clear_btn = gr.Button(\"清空对话\")\n",
    "    \n",
    "    # 绑定事件\n",
    "    recipe_btn.click(\n",
    "        fn=get_recipe,\n",
    "        inputs=dish_input,\n",
    "        outputs=recipe_output\n",
    "    )\n",
    "    \n",
    "    # 按回车键也可以发送\n",
    "    def respond(message, chat_history):\n",
    "        bot_message = chat_with_chef(message, chat_history)\n",
    "        chat_history.append((message, bot_message))\n",
    "        return \"\", chat_history\n",
    "    \n",
    "    msg.submit(respond, [msg, chatbot], [msg, chatbot])\n",
    "    send_btn.click(respond, [msg, chatbot], [msg, chatbot])\n",
    "    clear_btn.click(lambda: None, None, chatbot, queue=False)\n",
    "\n",
    "# 启动应用\n",
    "if __name__ == \"__main__\":\n",
    "    demo.launch(\n",
    "        \n",
    "        # 设置为True可以生成公共链接\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b1a07fff-ffbd-421b-9efd-1b6b2f028b47",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
